package com.easylinkin.sm.service.impl;

import com.alibaba.fastjson.JSON;
import com.easylinkin.sm.constant.DictConstant.Attach;
import com.easylinkin.sm.entity.I18n;
import com.easylinkin.sm.repository.I18nRepository;
import com.easylinkin.sm.service.I18nService;

import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.morn.boot.data.CrudServiceSupport;
import site.morn.core.CriteriaMap;

/**
 * 国际化服务
 *
 * @author wujie
 * @since 0.1.1,  2019/08/19
 */
@Slf4j
@Service
@Transactional
public class I18nServiceImpl extends CrudServiceSupport<I18n, Long, I18nRepository> implements
    I18nService {

  @Override
  public void saveAll(List<I18n> i18ns) {
    i18ns.forEach(x -> {
      if (Objects.nonNull(x.getId())) {
        this.update(x);
      } else {
        this.add(x);
      }
    });
  }

  @Override
  public void deleteByKeyAndModule(Long key, String module) {
    repository().deleteByKeyAndModule(key, module);
  }

  /**
   * 保存字典国际化
   *
   * @param attach 国际化map
   */
  @Override
  public void saveI18n(CriteriaMap attach, Long key, String module) {
    Object object = attach.get(Attach.I18N);
    if (Objects.nonNull(object)) {
      String jsonString = JSON.toJSONString(object);
      List<I18n> i18ns = JSON.parseArray(jsonString, I18n.class);
      if (Objects.isNull(key)) {
        i18ns.forEach(x -> x.setModule(module));
      } else {
        i18ns.forEach(x -> {
          x.setModule(module);
          x.setKey(key);
        });
      }
      this.saveAll(i18ns);
    }
  }
}
